package org.jaaksi.test.jpush.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import org.jaaksi.test.jpush.R;
import org.jaaksi.test.jpush.base.BaseActivity;
import org.jaaksi.test.jpush.model.push.MsgPushFeedBean;
import org.jaaksi.test.jpush.util.ConstantUtils;
import org.jaaksi.test.jpush.util.EventBusTool;
import org.jaaksi.test.jpush.util.SpFactory;
import org.simple.eventbus.Subscriber;

/**
 * Created by Fcy on 2016/1/24.
 */
public class MainActivity extends BaseActivity implements View.OnClickListener
{
	private TextView tv_tip_msg;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		EventBusTool.register(this);
		setContentView(R.layout.activity_main);

		findViewById(R.id.btn_msg).setOnClickListener(this);
		tv_tip_msg = findView(R.id.tv_tip_msg);

		initPoint();
	}

	// 含有 tag,当用户post事件时,只有指定了"tag_push"的事件才会触发该函数,执行在UI线程
	@Subscriber(tag = ConstantUtils.EventTag.UPDATE_POINT)
	public void update(String msg)
	{
		initPoint();
	}

	private void initPoint()
	{
		int count = 0;
		// tv_tip_msg.
		MsgPushFeedBean customerPushFeedBean = SpFactory.getInstance(this)
		        .getCustomerPushFeedData();
		if (customerPushFeedBean != null)
		{
			count = customerPushFeedBean.unReadErShou
			        + customerPushFeedBean.unReadNewHouse;
		}
		MsgPushFeedBean housePushFeedBean = SpFactory.getInstance(this)
		        .getHousePushFeedData();
		if (housePushFeedBean != null)
		{
			count = housePushFeedBean.unReadErShou
			        + housePushFeedBean.unReadNewHouse;
		}

		if (count == 0)
		{
			tv_tip_msg.setVisibility(View.GONE);
		}
		else
		{
			tv_tip_msg.setVisibility(View.VISIBLE);
			tv_tip_msg.setText(count + "");
		}
	}

	@Override
	public void onClick(View v)
	{
		Intent intent = new Intent(this, MessageListActivity.class);
		startActivity(intent);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		JPushInterface.onResume(this);
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		JPushInterface.onPause(this);
	}

	@Override
	protected void onDestroy()
	{
		EventBusTool.unregister(this);
		super.onDestroy();
	}

	/**
	 * 模拟二手推送消息
	 * 
	 * @param view
	 */
	public void addErShouMsg(View view)
	{
		MsgPushFeedBean housePushFeedData = SpFactory.getInstance(this)
		        .getHousePushFeedData();
		housePushFeedData.unReadErShou++;
		SpFactory.getInstance(this).setHousePushFeedData(housePushFeedData);
	}

	/**
	 * 模拟新房推送消息
	 * 
	 * @param view
	 */
	public void addNewMsg(View view)
	{
		MsgPushFeedBean housePushFeedData = SpFactory.getInstance(this)
		        .getHousePushFeedData();
		housePushFeedData.unReadNewHouse++;
		SpFactory.getInstance(this).setHousePushFeedData(housePushFeedData);
	}
}